<?php

namespace App\Http\Controllers\Admin;

use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Storage;
use Auth;

class FileController extends Controller
{
    public function upload_img(Request $request){
        if ($request->hasFile('course_imgs')) {
            return json_encode(["url" => $this->saveimg($request->file('course_imgs')->getRealPath(), $request->file('course_imgs')->getClientOriginalExtension())]);
        }
        if ($request->hasFile('headimgs')) {
            $user = $user = Auth::guard('home')->user();
            if(empty($user)){
                $return['code'] = 101;
                $return['message'] = '请重新登录';
                return json_encode($return);
            }
            $url = $this->saveimg($request->file('headimgs')->getRealPath(), $request->file('headimgs')->getClientOriginalExtension());
            User::where('id',$user->id)->update(['img'=>$url]);
            return json_encode(['code'=>0,"url" => $url]);
        }
    }
    //保存文件
    private function saveimg($img, $extension, $size = '')
    {
        $randomnum = create_guid();
        $filename = time() . $randomnum . '.' . $extension;
        $savepath = '/uploads';
        $targetPath = $_SERVER['DOCUMENT_ROOT'] . $savepath;
        if (!file_exists($targetPath)) {
            mkdir($targetPath, 0777, TRUE);
        }
        $fileurl = $savepath . '/' . $filename;
        $uploadfile = Storage::disk('public')->put($fileurl,file_get_contents($img));
        return $fileurl;
    }

    public function delimg(Request $r, FileController $file)
    {
        $url = $r->key;

        if(!empty($url)){
            if(Storage::disk('public')->exists($url)){
                if(Storage::disk('public')->delete($url)){
                    return 1;
                }
            }
        }
        return 0;
    }


}
